import axios, { AxiosError, AxiosInstance, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from 'axios';

const getAuthorization = () => {
  return 'Bearer ' + sessionStorage.getItem('token') || '';
};

const getLang = () => {
  return sessionStorage.getItem('lang') || 'en';
};

const toLogin = () => {
  window.location.href = `${window.location.origin}/manage/user/login?t=${new Date().getTime()}`;
};

const service: AxiosInstance = axios.create({
  withCredentials: false,
  timeout: 30000,
  headers: {
    Authorization: getAuthorization(),
  },
});

service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    config.headers.Authorization = getAuthorization();
    config.headers['Api-Lang'] = getLang();
    return config;
  },
  (error: AxiosError) => {
    return Promise.reject(error);
  },
);

service.interceptors.response.use(
  (response: AxiosResponse) => {
    console.log('response', response);
    if (response.status >= 200 && response.status < 300) {
      return response.data;
    } else {
      return Promise.reject(response);
    }
  },
  (error: AxiosError) => {
    // 处理错误响应
    if (error.response) {
      // 请求成功但状态码不在2xx范围内
      console.log('err', error);
      console.log('err', error.response);
      console.log('err', error.response.data);
      console.log('err', error.response.status);
      console.log('err', error.response.headers);
      if (error.response.data && (error.response.data.message || error.response.data.errmsg)) {
        error.message = error.response.data.message || error.response.data.errmsg;
      }
      if (error.response.status == 401) {
        setTimeout(() => {
          toLogin();
        }, 400);
      }
      return Promise.reject(error);
    } else if (error.request) {
      // 请求发出但没有收到响应
      console.log('err', error.request || 'Sorry! system failure, please try again later!');
      return Promise.reject(error);
    } else {
      // 在设置请求时发生了错误
      console.log('err' + error.message || 'Sorry! system failure, please try again later!');
      return Promise.reject(error);
    }
  },
);

export const http = {
  get<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return service.get(url, config);
  },

  post<T = any>(url: string, data?: object, config?: AxiosRequestConfig): Promise<T> {
    return service.post(url, data, config);
  },

  put<T = any>(url: string, data?: object, config?: AxiosRequestConfig): Promise<T> {
    return service.put(url, data, config);
  },

  delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return service.delete(url, config);
  },
};

export default service;
